<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/jsp/include/taglib.jsp"%>
<%@ include file="/jsp/include/headlist.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="${ctxStatic}/css/zTreeStyle/demo.css"
	type="text/css">
<link rel="stylesheet" href="${ctxStatic}/css/zTreeStyle/zTreeStyle.css"
	type="text/css">
<script type="text/javascript"
	src="${ctxStatic}/jquery/zTree/jquery.ztree.core.js"></script>
<script type="text/javascript"
	src="${ctxStatic}/jquery/zTree/jquery.ztree.excheck.js"></script>
<script type="text/javascript"
	src="${ctxStatic}/jquery/zTree/jquery.ztree.exedit.js"></script>
<script type="text/javascript"
	src="${ctxStatic}/jquery/zTree/ztree_customer.js"></script>

<SCRIPT type="text/javascript">
<!--//param-->
	var zTreeObj;
	
	//用户ID
	var userId = '${sessionScope.LOGIN_USER.id}';
	//是否为修志办
	var isChron='${sessionScope.isChron}';
	//params
	var Local = {
    		_type : '${param.type}',//当前查询的类型，卡片还是长编
    		_ticket:"1_1",
    		_lv:1,//查询层级数
    		_isEdit:false,
    		_pType:'catalog',//根目录
    		_pId:1,
    		_resourceType:'${param.resourceType}',
    		_op:'${param.op}',
    		_resourceCode:'${param.resourceCode}',
    		_delLv:9
    		
    	};  

	 $(function (){
		 //模态窗
		 $("#example").modal({backdrop:'static',keyboard:true,show:false});
		 $('#addNode').click(function(){
			 addNode('');
		 });
		 $('#reset').click(function(){
			 reset();
		 });
		 //alert('${sessionScope.isChron}'+"----"+'${param.op}');
		 
		//判断当前登录用户是否为修志办
		 if(isChron=='true' && Local._op==''){
			 Local._isEdit=true;
			 $('#addDiv').show();
			 
			 if(Local._type=='card')
				 $('#copy').show();
			 else
				 $('#copy').css('visibility','hidden');
			 
		 }else{
			 $('#addDiv').hide();
		 }
	 });
	 
	var setting = {
		async : {
			enable : true,
			url : getAsyncUrl,
			type : 'get',
			dataType : "json",//默认text 
			dataFilter : filter//异步返回后经过Filter 
		},
		view : {
			addHoverDom : addHoverDom,
			removeHoverDom : removeHoverDom,
			selectedMulti : false,
			showLine : false
		},
		edit : {
			enable : true,
			editNameSelectAll : true,
			showRemoveBtn: showRemoveBtn,
			showRenameBtn: showRenameBtn,
			removeTitle: "删除",
			renameTitle: "编辑",
		},
		data : {
			simpleData : {
				enable : true
			}
		},
		callback : {
			onClick : onClick,
			beforeDrag : beforeDrag,
			beforeEditName : beforeEditName,
			beforeRemove : beforeRemove,
			beforeRename : beforeRename,
			beforeExpand: zTreeBeforeExpand,
			beforeClick : beforeClick,//捕获单击节点之前的事件回调函数 
			//beforeCollapse: zTreeBeforeCollapse,//用于捕获父节点折叠之前的事件回调函数
			onRemove : onRemove,
			onRename : onRename,//编辑名称后调用的函数
			asyncSuccess : zTreeOnAsyncSuccess,//异步加载成功的fun 
			asyncError : zTreeOnAsyncError, //加载错误的fun 
			
			//onCollapse: zTreeOnCollapse//用于捕获节点被折叠的事件回调函数
			//onExpand: zTreeOnExpand//用于捕获节点被展开的事件回调函数
		}
	};
	function zTreeBeforeExpand(treeId, treeNode) {
		/* if(treeNode.property=='fourth')
			return false; */
			
		return true;
	};
	function zTreeOnExpand(event, treeId, treeNode) {
	    return false;
	};
	function zTreeOnCollapse(event, treeId, treeNode) {
		/* if(treeNode.property=='fourth')
			return false; */
			
		return true;
	};
	
	function zTreeBeforeCollapse(treeId, treeNode) {
		
		/* if(treeNode.property=='fourth')
			return false; */
			
		return true;
	}
	//获取异步加载的url
	function getAsyncUrl(treeId, treeNode,objFilter) {
		if (treeNode == null)
			return null;
		
		var url="${ctx}/catalog/" + treeNode.nid + "/child?ticket=" + Local._ticket
			+ "&lv=" + Local._lv+"&objFilter=";
		
		if(objFilter!=null)
			url+=objFilter;
		else
			url+='nobj,catalog';
			
		
		return url;
	}
	
	//过滤异步加载后的数据
	function filter(treeId, parentNode, childNodes) {
		if (!childNodes || !childNodes.data)
			return null;
		var data = childNodes.data;
		var ztree = getZtreeJSON(childNodes,'');
		/* $.each(data, function(i, n) {
			if (n.nobj == 'catalog') {
				ztree[i] = {
					id : n.nid,
					pId : n.pid,
					name : n.node.name,
					isParent : n.node.property == 'fourth' ? false : true,
					property : n.node.property,
					type : n.node.type
				};
			}
		}); */
		return ztree;
	}
	
	function beforeClick(treeId, treeNode) {
	}
	function zTreeOnAsyncError(event, treeId, treeNode) {
		alert("数据加载失败!");
	}
	function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
	}
	var log, className = "dark";
	function beforeDrag(treeId, treeNodes) {
		return false;
	}
	//编辑前
	function beforeEditName(treeId, treeNode) {
		zTreeObj.selectNode(treeNode);
		return confirm("进入节点 -- " + treeNode.name + " 的编辑状态吗？");
	}

	//删除前
	function beforeRemove(treeId, treeNode) {
		zTreeObj.selectNode(treeNode);
		var flag=false;
		//查询数据库中是否有子级节点未加载
		if(treeNode.isParent){
			if(confirm("存在子级目录,是否一起删除？")){
				$.jBox.tip('删除中,请等待.','loading');
				$.ajax({
						url : "${ctx}/catalog/"+treeNode.nid+"/child?r="+Math.random(),//暂时还未加载到card或summary
						type : 'get',
						data:{'ticket':Local._ticket,'lv':Local._delLv,'objFilter': 'nobj,catalog'},
						dataType:'json',
						async:true,
						success:function(result){
									var pIds=treeNode.pid+",";
									var pTypes=treeNode.pobj+",";
									var nIds=treeNode.nid+",";
									var nTypes=treeNode.nobj+',';
									var ruleTypeIds=1;
									
									//拼接自己当前节点
									
									//遍历取出所有子节点
									$.each(result.data,function(i,n){
										pIds+=n.pid;
										pTypes+=n.pobj;
										nIds+=n.nid;
										nTypes+=n.nobj;
										if(i<result.data.length-1){
											nIds+=",";
											pTypes+=",";
											nTypes+=",";
										} 
									});
									flag=delNode(treeNode,pIds,pTypes,nIds,nTypes,ruleTypeIds);
						},
						error:function(){alert("对不起！你的请求出现异常，请联系服务人员！");flag=false;}
					});
			}
		}else{
			//不是父节点
			flag=confirm("确认删除 节点 -- " + treeNode.name + " 吗？");
			if(flag)
				flag=delNode(treeNode,treeNode.pid,treeNode.pobj,treeNode.nid,treeNode.nobj,1);
		}
		return flag;
	}
	
	function delNode(treeNode,pIds,pTypes,nIds,nTypes,ruleTypeIds){
		  $.ajax({
	 			url  : "${ctx}/catalog/deleAll/"+nIds+"?ruleTypeId=1&r="+Math.random(),
				type : 'delete',
				dataType:'json',
	 			async:true,
	 			success:function(result){
	 					 $.jBox.closeTip();
						 if(result.info.success){
							zTreeObj.removeNode(treeNode);
							alert('删除成功.');
							parent.refresh('');
						}else
							alert('删除失败.');
	 			}	
		 }); 
			
		 //解除绑定关系
// 		 $.ajax({
// 			url : "${ctx}/api/relation/unbind?r="+Math.random(),
// 			type : 'post',
// 			data:{pId:pIds,pType:pTypes,nId:nIds,nType:nTypes,ruleTypeId:ruleTypeIds},
// 			dataType:'json',
// 			async:false,
// 			success:function(result){
// 				if(result.info.success){
// 					$.ajax({//修改catalog表中当前目录状态
// 						url : "${ctx}/catalog/"+nIds+"?r="+Math.random(),
// 						type : 'delete',
// 						data:null,
// 						dataType:'json',
// 						async:true,
// 						success:function(data){
// 							var flag=data.info.success;
// 							//判断是否为父节点（不为最顶层父节点）
// 							if(flag){
// 								if(treeNode.level>0)
// 									refreshParentNode();
// 								/* else
// 									refreshNode(); */
// 							}
// 							return flag;
// 						}
// 					});
// 				}
// 			}
// 		});   
	}
	//删除
	function onRemove(e, treeId, treeNode) {
		
	}

	//编辑时
	function beforeRename(treeId, treeNode, newName, isCancel) {
		var nodes = zTreeObj.getSelectedNodes();
		var flag=false;
		if (newName.length == 0) {
			//alert("节点名称不能为空.");
			parent.$.jBox.tip('节点名称不能为空，按ESC键退出.','warning');
			setTimeout(function() {zTreeObj.editName(treeNode)}, 10);
			return false;
		} else {
				flag=isRepetition(treeNode,newName,'edit');
				if(flag){
				  $.ajax({
						url:'${ctx}/catalog',
						type:'post',
						dataType:'json',
						data:{id:treeNode.nid,name:newName},
						success:function(data,status,xhr){
							if(!data.info.success)
								zTreeObj.cancelEditName(treeNode.name);
						},
						error:function(){
							alert("对不起！你的请求出现异常，请联系服务人员！");
						}
					});  
				}
			}
		return flag;
		}
	
	var childrenNodes;
	function isRepetition(treeNode,newName,operation){
		var nodes;
		childrenNodes=[];
		//判断是新增节点还是编辑节点
		if(operation=='edit'){
			if (treeNode.name == newName)
				return true;
			
			if(treeNode.level>0){//子节点
				nodes= treeNode.getParentNode().children;//获取同级节点数量
			}else{//根节点
				nodes=zTreeObj.getNodes();
			}
		}else if(operation=='add'){
			
			if(!treeNode){
				//添加父节点
				nodes=zTreeObj.getNodes();	
				//初始化父节点数据
				//$("input[name='type']").val(Local._type);
				$("input[name='property']").val('1');
				
			}else{
				//若为新增，则获取子级节点
				//1.子级节点是否已加载
				//已加载则直接获取，未加载则发送请求加载
				if(!treeNode.zAsync && treeNode.isParent){
					//强制异步刷新
					$.ajax({
					    url :getAsyncUrl(treeNode.tId,treeNode,""),
						type : 'get',
						dataType:'json',
						data:null,
						async:false,
						success:function(result){
							//判断当前节点下是否有字节点为card或summary
							nodes=getZtreeJSON(result,false);
							childrenNodes=result;
							//treeObj.reAsyncChildNodes(nodes[0], "refresh");
						}
					});
				}else{
					nodes=treeNode.children;	
				}
			}
		}
		var flag=true;
		var codes=[];
		if(nodes!=null && nodes.length>0){
			$.each(nodes,function(i,node){
				//得到当前节点code
				codes[i]=node.code;
				if (newName == node.name) {
				    alert('名称不能重复.');
					var zTree= $.fn.zTree.getZTreeObj("treeDemo");
					zTree.cancelEditName();
					flag=false;
					childrenNodes=[];
					codes=[];
					return false;
				}
			});
		}
		
		if(operation=='add'){
			var code='01';
			if(codes!=null &&codes.length>0){	
		        
				/* codes.sort(function(a,b){
		            return a-b;
		        });  */
		        codes.sort(function(a,b){
		            return a-b;
		        });
		        
		        code=parseInt(codes[codes.length-1])+1;
		        
		        if((code+'').length<2){
		        	code="0"+code;
		        }
			}
	        $("input[name='code']").val(code);
	        if(!!treeNode)
	        	$("input[name='parentCode']").val(treeNode.parentCode+"-"+code);
	        else
	        	$("input[name='parentCode']").val(Local._resourceCode+"-"+code);
		}
		return flag;
	}

	function getCardOrSummary(result){
		var data=new Array();
		if(result!==null)
			return data;
		if(result.info.success){
			if(result.data.length>0){
				$.each(result.data,function(i,n){
					//1.查询该节点下是否有子节点，显示不同的图标
					if (n.nobj == type) {
					data.push({
							nobj:n.nobj,
							pobj:n.pobj,
							nid:n.nid,
							pid:n.pid
						});
					}
				});
			}
		}
		
		return data;
	}
	
	function getZtreeJSON(result,_isParent){
		
		var data=[];
		if(!result.info.success)
			return data;
		
		if(result.data!=null){
				$.each(result.data,function(i,n){
					//1.查询该节点下是否有子节点，显示不同的图标
					data[i] = {
							id : n.nobj+"_"+n.nid,
							pId :n.pobj+"_"+n.pid,
							name : n.node.name,
							isParent : _isParent=='' ? isParent('${ctx}/catalog/'+n.nid+'/child?ticket='+Local._ticket+'&objFilter=nobj,catalog&lv=1') : _isParent,
							property : n.node.property,
							type : n.node.type,
							nobj:n.nobj,
							pobj:n.pobj,
							nid:n.nid,
							pid:n.pid,
							noRemoveBtn:Local._isEdit,
							noEditBtn:Local._isEdit,
							noAddBtn:Local._isEdit,
							code:n.node.code,
							resourceType:n.node.resourceType,
							parentCode:n.node.parentCode
						};
				});
		}
	
		
		data.sort(getSortFun('asc', 'code'));
		return data;
	}
	
	
	function showAddPanel(treeNode){
		reset();
		parent.$.jBox(
			$("#example").html(), 
			{
				title:"添加子目录", 
				buttons: { '添加': 1, '取消': 0 },
				submit: function (v, h, f) {
				  	if (v == 0) {
				  		reset();
                        return true; // close the window
                    }					
				 	h.find('[type=text],[type=hidden]').each(function(){
				 		$("input[name="+$(this).attr('name')+"]").val($(this).val());
				 	});			
				 	//$("#addNode").trigger('click');
					return addNode(treeNode);
				}
			}
		);
	}
	
	//添加节点
	function addNode(treeNode){  
		 //treeNode.children [n] .isParent
		 	var _$name=$("input[name='name']");

			if(_$name.val()=='' ||  _$name.val()==null){
				alert('请输入目录名称.');
				return false;
			}

			if(treeNode==null || treeNode==''){
				$("input[name='property']").val("1");
			}else{
				var myProperty=parseInt(treeNode.property)+1;
				$("input[name='property']").val(myProperty);
			}
		
			var flag=isRepetition(treeNode,_$name.val(),'add');
			if(flag){
				 $.ajax({
				    url : "${ctx}/catalog",
					type : 'post',
					dataType:'json',
					data:$("#form").serialize(),
					success: function(result, status, xhr) {
						 reset();
						 //判断是否新增成功，则绑定关系
						 if(result.info.success){
							 var pId=Local._pId;
							 var pType=Local._pType;
							 var nId=result.data.id;
							 var nType='catalog';
							 //判断添加的是父节点还是子节点
							 if(!!treeNode){
								 pId=treeNode.nid;
								 pType=treeNode.nobj;
							 }
							  var ruleTypeId=1;
							  //不需要自动移
							  /*childrenNodes=getCardOrSummary(childrenNodes);
							 //判断当前父节点下的子节点是否为card或summary
							 if(childrenNodes!=null && childrenNodes.length>0){
								 
								 //解除关联对象类型及ID
								 //解除card或summary与当前节点的关系
								 var pIds1='';
								 var pTypes1=treeNode.nobj;
								 var nIds1='';
								 var nTypes1=type;
								 
								 var pIdNew='';
								 
								 //同时并把它绑定到新增节点目录下
								 for (var i=0;i<childrenNodes.length;i++) {
									if(childrenNodes[i].nobj==type){
										//得到card或summary
										pIds1+=treeNode.nid;
										nIds1+=childrenNodes[i].nid;
										
										pIdNew+=result.data.id;//新父节点ID
										
										if(i<childrenNodes.length-1){
											pIds1+=",";
											nIds1+=",";
											pIdNew+=',';
										} 
									}									
								 }
								 //解除当前节点与该节点下card或summary的关系
								 unbind({pId:pIds1,pType:pTypes1,nId:nIds1,nType:nTypes1,ruleTypeId:ruleTypeId});
								 bind({pId:pIdNew,pType:pType,nId:nIds1,nType:nTypes1,ruleTypeId:ruleTypeId});
							 }  */
							 
							 
							$.post('${ctx}/api/relation/bind?r='+Math.random(),{pId:pId,pType:pType,nId:nId,nType:nType,ruleTypeId:ruleTypeId},
									function(data){
								//非根节点刷新
								if(treeNode!=null && treeNode!=''){
									if((!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) || treeNode.zAsync){
										
									}else{ 
										zTreeObj.reAsyncChildNodes(treeNode, "refresh");
									}
								}
								zTreeObj.addNodes(treeNode, 
										{id :nType+'_'+result.data.id,
										 pId :treeNode==null ? Local._pId : treeNode.id ,
										 name : result.data.name,
										 isParent:false,
										 pobj:treeNode==null ? Local._pType : nType ,
										 nobj:nType,
										 property : result.data.property,
										 nid:result.data.id,
										 pid:treeNode==null?Local._pId:treeNode.nid,
										 tId:"treeDemo_"+nType+"_"+result.data.id,
										 noRemoveBtn:Local._isEdit,
										 noEditBtn:Local._isEdit,
										 noAddBtn:Local._isEdit,
										 code:result.data.code,
										 resourceType:result.data.resourceType,
										 parentCode:result.data.parentCode
										});
								
								alert('添加成功');
								parent.$.jBox.close(true);
								/* else{
									zTreeObj.addNodes(
											treeNode, {id :nType+'_'+result.data.id,pId : pType+'_'+treeNode.id,name : result.data.name,isParent:false,pobj:pType,nobj:nType});
								}  */
								
							},'json').error(function(){reset();});
							
							/* var data=bind();
							 if(data.info.success){
									//非根节点刷新
									if(result.data.property!='first' && treeNode!=null){
										if((!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) || treeNode.zAsync){
											zTreeObj.addNodes(treeNode, {id :nType+'_'+result.data.id,pId : pType+'_'+treeNode.id,name : result.data.name,isParent:false,pobj:pType,nobj:nType});
										}else{ 
											zTreeObj.reAsyncChildNodes(treeNode, "refresh");
										}
									}else{
										zTreeObj.addNodes(treeNode, {id :nType+'_'+result.data.id,pId : pType+'_'+treeNode.id,name : result.data.name,isParent:false,pobj:pType,nobj:nType});
									} 
									
							} */
						 }
			        }, 
			        error: function() {
			        	reset();
			           	alert("对不起！你的请求出现异常，请联系服务人员！");
			           	return false;
					}
				});	 
			} else{
				 _$name.val('');
			}
	
	}
	
	
	function bind(data){
		$.post('${ctx}/api/relation/bind?r='+Math.random(),data,
				function(data){
				return data;			
			},'json').error(function(){reset();});
	}
	
	function unbind(data){
		
		$.post('${ctx}/api/relation/unbind?r='+Math.random(),data,
				function(data){
				return data;			
			},'json').error(function(){});
	}
	
	
	//编辑名称后调用的函数
	function onRename(e, treeId, treeNode, isCancel) {
	}
	function showRemoveBtn(treeId, treeNode) {
		return treeNode.noRemoveBtn;
	}
	function showRenameBtn(treeId, treeNode) {
		return treeNode.noEditBtn;
	}
	var newCount = 1;
	//新增节点
	function addHoverDom(treeId, treeNode) {
		/* if(treeNode.property=='fourth')
			return; */
		
		if(treeNode.noAddBtn/*  && treeNode.property!='fourth' */){
			var sObj = $("#" + treeNode.tId + "_span");
			if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0)
				return;
			var addStr = "<span class='button add' data-toggle=\"modal\" id='addBtn_" + treeNode.tId+ "' title='新增' onfocus='this.blur();'></span>";
			sObj.after(addStr);
			
			var btn = $("#addBtn_" + treeNode.tId);
			if (btn)
				btn.bind("click", function() {
					zTreeObj.selectNode(treeNode);
					//得到当前节点层级数
					var level = treeNode.level;
					if (level < 0) {
						parent.$.jBox.tip('请选择父节点.','warning');
						return false;
					}
					showAddPanel(treeNode);
				});
		}else{
			return false;
		}
	};
	
	function reset(){
		 $("input[name='name']").val('');
		 $("input[name='property']").val('');
		 $("input[name='code']").val('');
		 $("input[name='parentCode']").val('');
		 $('#example').modal('hide');
	}
	
	
	function removeHoverDom(treeId, treeNode) {
		$("#addBtn_" + treeNode.tId).unbind().remove();
	};
	function selectAll() {
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		zTree.setting.edit.editNameSelectAll = $("#selectAll").attr("checked");
	}
	function onClick(event, treeId, treeNode, clickFlag) {
		//得到当前节点ID以及父节点ID
		var nId = treeNode.nid;
		var pId = treeNode.pid;
		 if(parent.onCatalogSelected){
			 var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			 parent.onCatalogSelected(treeNode,zTreeObj);
		 }
	}
	$(document).ready(function() {
		//加载父节点
		zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, null);

		$("#selectAll").bind("click", selectAll);
		
		$.jBox.tip("加载中...", 'loading');
		//判断是否为修志专员
		if(isChron=='true'){
			//查询当前用户所在用户组  /chron/api/user/2600/parent?ticket=1_1&objFilter=nobj,group
			$.get('${ctx}/api/user/'+userId+'/parent',{
				'ticket':Local._ticket,'objFilter':'nobj,group','lv':1
			},function(result){
				//根据用户组查询该用户组的目录权限 http://localhost:8080/chron/api/group/8/child?ticket=1_1&objFilter=nobj,catalog&lv=2
			     $.get('${ctx}/api/group/'+result.data[0].nid+'/child?r='+Math.random(),{
			    	 'ticket':Local._ticket,'objFilter':'nobj,catalog','lv':3	    	 
			     },function(result2) {
						var zTreeData =new Array();	
						if(!result2.info.success)
							return;
						$.each(result2.data,function(i,n){
							//同时判断当前为那个志下面的card或summary
							if(n.pobj=='catalog' && n.nobj=='catalog' &&  n.node.type==Local._type  &&  Local._resourceType==n.node.resourceType){
								zTreeData.push({
										id : n.nobj+"_"+n.nid,
										pId : n.pobj+"_"+n.pid,
										name : n.node.name,
										isParent : isParent('${ctx}/catalog/'+n.nid+'/child?ticket='+Local._ticket+'&lv=1&objFilter=nobj,catalog'),
										property : n.node.property,
										type : n.node.type,
										nobj:n.nobj,
										pobj:n.pobj,
										nid:n.nid,
										pid:n.pid,
										tId:"treeDemo_"+n.nobj+"_"+n.nid,
										noRemoveBtn:Local._isEdit,
										noEditBtn:Local._isEdit,
										noAddBtn:Local._isEdit,
										code:n.node.code,
										resourceType:n.node.resourceType,
										parentCode:n.node.parentCode
									});
							}
						});
						//根据code升序
						//zTreeData.sort(getSortFun('asc', 'code'));
						
						zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zTreeData);
						
						$.jBox.closeTip();
					}, 'json');
			},'json');	
		}else{
			  $.get('${ctx}/catalog/'+Local._pId+'/child?r='+Math.random(),{
			    	 'ticket':Local._ticket,'objFilter':'nobj,catalog','lv':Local._lv	    	 
			     },function(result) {
						var zTreeData =new Array();
						
						if(!result.info.success)
							return;
						$.each(result.data,function(i,n){
							//同时判断当前为那个志下面的card或summary
							if(n.node.type==Local._type  &&  Local._resourceType==n.node.resourceType){
								zTreeData.push({
										id : n.nobj+"_"+n.nid,
										pId : n.pobj+"_"+n.pid,
										name : n.node.name,
										isParent : isParent('${ctx}/catalog/'+n.nid+'/child?ticket='+Local._ticket+'&lv=1&objFilter=nobj,catalog'),
										property : n.node.property,
										type : n.node.type,
										nobj:n.nobj,
										pobj:n.pobj,
										nid:n.nid,
										pid:n.pid,
										tId:"treeDemo_"+n.nobj+"_"+n.nid,
										noRemoveBtn:Local._isEdit,
										noEditBtn:Local._isEdit,
										noAddBtn:Local._isEdit,
										code:n.node.code,
										resourceType:n.node.resourceType,
										parentCode:n.node.parentCode
									});
							}
						});
						//根据code升序
						//zTreeData.sort(getSortFun('asc', 'code'));
						
						zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zTreeData);
						$.jBox.closeTip();
					}, 'json');
			
		}
		
		//catalogList  parent
// 		console.log($("#catalogList",window.parent.document).attr('height'));
		
	});
	
	function getSortFun(order, sortBy) {
	    var ordAlpah = (order == 'asc') ? '>' : '<';
	    var sortFun = new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + '?1:-1');
	    return sortFun;
	}
	
	/** 
     * 刷新当前节点 
     */  
    function refreshNode() {  
        /*根据 treeId 获取 zTree 对象*/  
        var zTree = $.fn.zTree.getZTreeObj("treeDemo"),  
        type = "refresh",  
        silent = false,  
        /*获取 zTree 当前被选中的节点数据集合*/  
        nodes = zTree.getSelectedNodes();  
        /*强行异步加载父节点的子节点。[setting.async.enable = true 时有效]*/  
        zTree.reAsyncChildNodes(nodes[0], type, silent);  
    }  

    /** 
     * 刷新当前选择节点的父节点 
     */  
    function refreshParentNode() {  
        var zTree = $.fn.zTree.getZTreeObj("treeDemo"),  
        type = "refresh",  
        silent = false,  
        nodes = zTree.getSelectedNodes();  
        /*根据 zTree 的唯一标识 tId 快速获取节点 JSON 数据对象*/  
        var parentNode = zTree.getNodeByTId(nodes[0].parentTId);  
        /*选中指定节点*/  
        zTree.selectNode(parentNode);  
        zTree.reAsyncChildNodes(parentNode, type, silent);  
    }  
    
    
    //导出长编目录
    function copyCatalogs(){
    	//判断是否有目录
    	var nodes=zTreeObj.getNodes();
    	if(nodes==0){
    		parent.$.jBox.tip('请先添加卡片目录.','warning');
    		return;
    	}
    	
    	if(!confirm("是否生成长编目录？"))
    		return;
    	//判断该志下面是否已有长编目录	
    	$.get('${ctx}/catalog/'+Local._pId+'/child?r='+Math.random(),
    			{'ticket':Local._ticket,'objFilter':'nobj,catalog','lv':1},
    		function(result){
	   			if(result.info.success){
	   				if(confirm("该志下面已有长编目录,是否清除现有目录继续导出？")){
	   				  	$.jBox.tip("目录生成中...", 'loading');
	   					$.get('${ctx}/catalog/'+Local._pId+'/child?r='+Math.random(),
	   			    			{'ticket':Local._ticket,'objFilter':'nobj,catalog','lv':Local.delLv},
	   			    			function(result2){
		   			 	   			var ids='';
		   				   			$.each(result.data,function(i,n){
		   				   				if(n.node.resourceType==Local._resourceType  && n.node.type=='summary'){
		   				   					ids+=n.node.id+",";
		   				   				}
		   				   			});
		   				   			ids=ids.substring(0,ids.length-1);
	   			   					$.ajax({
	   			   			 			url  : "${ctx}/catalog/deleAll/"+ids+"?ruleTypeId=1&r="+Math.random(),
	   			   						type : 'delete',
	   			   						dataType:'json',
	   			   			 			async:true,
	   			   			 			success:function(result){
	   			   			 				    //判断删除的是否为根节点
	   			   			 					/*  if(treeNode.level>0)
	   			   									refreshParentNode();
	   			   			 					else  */
	   			   								  if(result.info.success){
	   			   										addCatalog(nodes);
	   			   								  }else
	   			   										alert('生成失败.');
	   			   			 			}	
	   			   					 });
	   			    			},
	   			    	'json');
	   				}
	   			}else{
	   				//addCatalog(nodes);
	   		}
    	},'json');
    }
    
    
    
    function addCatalog(nodes){
    	
    	  if(nodes==null)
    		  return;
    	  
    	  var ids='';
    	  //得到父节点ID
    	  $.each(nodes,function(i,n){
    		  ids+=n.nid+",";
    	  });
    	  
    	  ids=ids.substring(0,ids.length-1);
    	  $.ajax({
   			 			url  : "${ctx}/catalog/copyCatalogs?r="+Math.random(),
   						type : 'post',
   						data:{'ids':ids ,'ticket':Local._ticket,'objFilter':'nobj,catalog','lv':Local._lv},
   						dataType:'json',
   			 			async:true,
   			 			success:function(result){
   			 			 	//$.jBox.tip("导出中...", 'loading');
   			 				$.jBox.closeTip();
   			 				parent.$.jBox.tip('导出长编目录成功，请点击查看.','warning');
   			 			},error:function(){
   			 				$.jBox.closeTip();
   			 			}
    	  });
    }
</SCRIPT>
<style type="text/css">
body{
	background: #efefef;
}
.ztree li span.button.add {
	margin-left: 2px;
	margin-right: -1px;
	background-position: -144px 0;
	vertical-align: top;
	*vertical-align: middle
}

/* .ztree li span.button.ico_docu { */
/* 	background-position: -110px -16px */
/* } */
.ul-form li label {
		width: 110px;
}


.input01{
	width: 200px
}


</style>
</HEAD>
<BODY >
<!-- 		<ul  class="ul-form" style="display: none;" id='addDiv'  > -->
<!-- 			<li class="btns"><input data-toggle="modal" onclick="showAddPanel();" class="btn btn-primary" type="button" value="添加根目录"/></li> -->
<!-- 		    <li class="btns"><input data-toggle="modal" onclick="showAddPanel();" class="btn btn-primary" type="button" value="导出长编目录"/></li> -->
<!-- 		</ul> -->
			<div style="display: none;" id='addDiv' class="input01"><a  style="width: 85px" href="javascript:showAddPanel();">添加根目录</a><a  id="copy" style="width: 85px;" onclick="javascript:copyCatalogs();"  href="javascript:void(0)" >导出长编目录</a></div>			
	<div class="left">
		<ul id="treeDemo" class="ztree"></ul>
	</div>
	
	<div>
		<form id='form' >
		<div id="example" class="modal hide fade in" style="display: none;">
<!-- 			<div class="modal-header">
				<a class="close" data-dismiss="modal">×</a>
				<h3>添加子目录</h3>
			</div> -->		
			<div class="modal-body">
			<ul class="ul-form" >
			<li style="list-style: none;"><label>目录名称</label>
			<input type="text" name='name' maxlength="50" class="input-medium" value=""/>
			</li>
			</ul>
			    <input type="hidden" name='code' maxlength="50" class="input-medium" value=""/>
			    <input type="hidden" name='parentCode' maxlength="50" class="input-medium" value=""/>
				<input type="hidden" name='type' maxlength="50" class="input-medium" value="${param.type}"/>
				<input type="hidden" name='property' maxlength="50" class="input-medium" value=""/>
				<input type="hidden" name='resourceType' maxlength="50" class="input-medium" value="${param.resourceType}"/>
			</div>
			<div class="modal-footer" style="display:none;">
			<input id="addNode" class="btn btn-primary" type="button" value="添加"/>
			<input class="btn btn-success"  data-dismiss="modal" id='reset' type="button"  value="关闭"/>
<!-- 				<a id='addNode' class="btn btn-success fr" >添加</a> -->
<!-- 				 <a href="#" class="btn btn-success fr"  data-dismiss="modal">关闭</a> -->
			</div>
		</div>
		</form>
	</div>
</BODY>
</HTML>